package com.interauto.service;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * 提供http请求的线程池用的。避免每次请求都重新走tcp连接。本地测试，在循环请求里，速度是要快
 */
@Component
public class HttpClientPool {

    private CloseableHttpClient httpClient;

    @PostConstruct
    private void init(){
        PoolingHttpClientConnectionManager connectionManager=new PoolingHttpClientConnectionManager
                (6000, TimeUnit.MINUTES);  //这个值是包在网络传输中的存活时间,一般就60秒
        connectionManager.setMaxTotal(1000); //最达的tcp连接数
        connectionManager.setDefaultMaxPerRoute(50); //单个路由最大的tcp连接数
        
        ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
                long keepAlive = super.getKeepAliveDuration(response, context);
                if (keepAlive == -1) {
                    keepAlive = 60 * 1000;
                }
                return keepAlive;
            }
        };
        httpClient= HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setKeepAliveStrategy(keepAliveStrategy)
                .setConnectionTimeToLive(60 * 1000, TimeUnit.MILLISECONDS)
                .disableAutomaticRetries().build();
    }

    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public void setHttpClient(CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public static void main(String[] args) throws Exception{
        HttpClientPool httpClientPool=new HttpClientPool();
        httpClientPool.init();
        CloseableHttpClient httpClient=httpClientPool.getHttpClient();
        URIBuilder urlBuilder=new URIBuilder("http://www.nmc.cn/rest/relevant/430?_=1609576583006");
        HttpGet httpGet=new HttpGet(urlBuilder.build());
        CloseableHttpResponse response=httpClient.execute(httpGet);
        HttpEntity httpEntity=response.getEntity();
        InputStream inputStream=null;
        StringBuilder buf=new StringBuilder();
        try{
            inputStream=httpEntity.getContent();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
            String s;
            while ((s=bufferedReader.readLine())!=null){
                buf.append(s);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(buf.toString());
    }
}
